package com.pubinfo.passbook.api.config;

import com.alibaba.fastjson.JSONObject;
import com.pubinfo.passbook.common.model.vo.base.JsonResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.*;

/**
 * EIP鉴权过滤器
 */
@Slf4j
public class MyFilter implements Filter {
  
  /**
   * 可以放行的路径 [模糊匹配]
   */
  private static final List<String> ALLOW_PATHS = Arrays.asList(
      "/api/eip/login",
      "/api/eip/callback",

          "/api/file/acctDownload",

          "css",
      "js",
      "html",
      "webjar",
      
      // swgger
      "swagger",
      "api-docs"
  );
  
  @Value("${eip.cas.front-uri}")
  private String loginUrl;
  
  @Override
  public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
    
    HttpServletResponse response = (HttpServletResponse) servletResponse;
    HttpServletRequest hrequest = (HttpServletRequest) servletRequest;
    HttpServletResponseWrapper wrapper = new HttpServletResponseWrapper((HttpServletResponse) servletResponse);
  
    response.setHeader("Access-Control-Allow-Origin", "*");
    response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE,PUT,HEAD");
    // response.setHeader("Access-Control-Allow-Credentials", "true");//true代表允许携带cookie
    //   response.setHeader("Access-Control-Max-Age", "3600");
    response.setHeader("Access-Control-Allow-Headers", "access-control-allow-origin, authority, content-type, version-info, X-Requested-With, token, x-action, menu, subMenu, content-disposition");
    
    if (hrequest.getMethod().equals(RequestMethod.OPTIONS.name())) { // OPTION 請求放行
      filterChain.doFilter(servletRequest, servletResponse);
      return;
    }
    
    String uri = hrequest.getRequestURI();
    
    String token = hrequest.getHeader("token");
    
    if (StringUtils.isNotBlank(token)) { // 令牌存在放行
      filterChain.doFilter(servletRequest, servletResponse);
      return;
    }
    
    for (String allowPath : ALLOW_PATHS) {
      if (uri.contains(allowPath)) {
        filterChain.doFilter(servletRequest, servletResponse);
        return;
      }
    }

    // 返回401
    response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
    response.setContentType("application/json; charset=UTF-8");
    response.getWriter().write(
            JSONObject.toJSONString(
                    JsonResult.error(HttpServletResponse.SC_UNAUTHORIZED, "未登录")
            )
    );
    
  }
  
  @Override
  public void destroy() {
  }
  
  @Override
  public void init(FilterConfig filterConfig) throws ServletException {
  }
}
